﻿<template>
  <div id="p_none" class="p_task">     
    <actionsheet v-model="showEditBtn" :menus="asBtnCurr" show-cancel @on-click-menu="chooseEdit"></actionsheet>   
    <div v-if="mode_vip"  style="display:flex;border-bottom: 1px solid #eee;background-color:#f0f0f0;">
            <!-- v-if="btnsShow" -->
            <button-tab v-model="btnType" class="timeBtn">
                <button-tab-item @on-item-click="onTypeChange(index)" :value="it" v-for="(it, index) in btns" :key="index">{{it}}</button-tab-item>
            </button-tab>
            <div  ref="dayScrol" style="width: 100%;overflow:scroll;-webkit-overflow-scrolling:touch;background-color:#fff;">
              <tab v-model="weekSelect" v-if="btnType==0 || btnType==1" :style="{width: weekBtns.length*80 + 'px'}" bar-active-color="#37aefc" :line-width="0">
                <tab-item ref="weeks" :selected="weekSelect === index" @on-item-click="onSortItem(it,index,1)" active-class="active-tab" :value="it" v-for="(it, index) in weekBtns" :key="index">{{it.label}}</tab-item>  
              </tab>
              <tab v-model="monthSelect" v-if="btnType==2" :style="{width: monthBtns.length*40 + 'px'}" bar-active-color="#37aefc" :line-width="0">
                <tab-item ref="months" :selected="monthSelect === index"  @on-item-click="onSortItem(it,index,2)" active-class="active-tab" :value="it" v-for="(it, index) in monthBtns" :key="index">{{it.label}}</tab-item>  
              </tab>
              <tab v-model="yearSelect" v-if="btnType==3" :style="{width: yearBtns.length*60 + 'px'}" bar-active-color="#37aefc" :line-width="0">
                <tab-item ref="years" :selected="yearSelect === index"  @on-item-click="onSortItem(it,index,3)" active-class="active-tab" :value="it" v-for="(it, index) in yearBtns" :key="index">{{it.label}}</tab-item>  
              </tab>
            </div>
    </div>
    <div style="height:3px;" v-show="!weekEdit"></div>
    <scroller v-model="pullStatus" lock-x scrollbar-y use-pulldown :pulldown-config="pullDownConfig2" use-pullup @on-pulldown-loading="changeVip" :pullup-config="pullupConfig2" :height="scrollHeight" ref="scroll" @on-pullup-loading="loadNext" :scroll-bottom-offset="300">
        <group class="group0">
            <div v-if="nonesLen==0" style="text-align:center;" ><img src="/static/z39h5/img/none.png" width="200" /></div>
            <swipeout>
                <swipeout-item v-if="index<pageShowNum" @on-open="actionOpenDone(item, index)" v-for="(item, index) in nonesArr" :key="index" ref="action" @longtap="doLongtap">
                    <div slot="right-menu">
                        <swipeout-button @click.native="onDelClick(item,index)" type="default">取消</swipeout-button>
                        <swipeout-button @click.native="goTask(item,index)" type="warn">详情</swipeout-button>
                        <swipeout-button @click.native="onTaskDue(item,index)" type="primary">{{dayshow(item,daySwipe)}}</swipeout-button>
                    </div>
                    <div slot="left-menu">
                        <swipeout-button @click.native="actionSwipeDone(item, index)" type="primary">{{item.state!='done'?'完成':'取消完成'}}</swipeout-button>
                    </div>
                    <div slot="content" class="vux-1px-t" v-bind:class="{task_going:item.state=='started',task_done:item.state=='done',task_toggle:item.state=='toggle',task_cancle:item.state=='cancelled',task_curr: taskCurr == item}" @touchstart="doTaskTouchStart(item,index)">
                        <cell @click.native="showTasnBtn(item,index)" :title="showDue(item) +item.title" :inline-desc="(item.state!=''||(item.tags&&item.tags.need))?showTaskDesc1(item):item.desc">
                          <div slot="icon" @click.stop="playtask(item,'todo')">
                              <img src="/static/z39h5/img/logo.png" style="width:50px;height:50px;"/>
                              <span class="taskCount">{{index+1 + "/" + nonesLen}}</span>
                          </div>
                        </cell>
                    </div>
                </swipeout-item>
            </swipeout>
        </group>
        <div slot="pullup" class="xs-plugin-pullup-container xs-plugin-pullup-up" style="position: absolute; width: 100%; height: 40px; bottom: -40px; text-align: center;">
            <span v-show="pullStatus.pullupStatus === 'default'"></span>
            <span class="pullup-arrow" v-show="pullStatus.pullupStatus === 'down' || pullStatus.pullupStatus === 'up'" :class="{'rotate': pullStatus.pullupStatus === 'up'}">Loading</span>
            <span v-show="pullStatus.pullupStatus === 'loading'"></span>
        </div>
     </scroller>     
    </div>
</template>
<script>
import moment from "moment";
import _ from '../../../static/jslib/underscore-min.js';
import Vue from 'vue';

import api from '../../api';
import {
    mapState,
    mapActions
} from 'vuex'

import { taskAndTag } from "../mixin";
import { help } from "../mixinApp";
import TaskAdd from "../TaskAdd";

import {
    TransferDomDirective as TransferDom,Toast,Swipeout,SwipeoutItem,SwipeoutButton,XButton,Group,Cell,Tab,TabItem,
    Box,XInput,XTextarea,Flexbox,Actionsheet, FlexboxItem,Datetime,Scroller,ButtonTab,ButtonTabItem
} from 'vux'
var defaultTask = [{title:"创建任务:点击下方'+'号添加想做的事",desc:"",state:""},{title:"完成:向右滑动完成您的梦想任务",desc:"",state:""},{title:"取消:向左滑动取消计划",desc:"",state:""},{title:"播放:点击图标",desc:"",state:""}];
var firstrun = localStorage.getItem("firstrun");
var lastTaskLen,autoOpenid;

export default {
    directives: {TransferDom},
    components: {        
        Toast,Swipeout,SwipeoutItem,SwipeoutButton,XButton,Group,Cell,Tab,TabItem,
        Box,XInput,XTextarea,Flexbox,Actionsheet, FlexboxItem,Datetime,Scroller,ButtonTab,ButtonTabItem,TaskAdd
    },    
    mixins: [taskAndTag,help],    
    computed: {        
        ...mapState({
            isNavShow: state => state.vux.isNavShow,
            uid: state => state.vux.uid,
            taskAll: state => state.z39.taskAll,
            tagDic: state => state.z39.tagDic,
                        
            tagitemDic: state => state.z39.tagitemDic,
        })
    },
    watch: {
        "taskAll":{handler(){
            this.nonesCpted();
        },  deep: true },
        "uid":function(){
            this.getInitData();
        },
        "filtersDue":function(){
            this.taskAddExtChange();
        },
        "btnType":function(){
            this.taskAddExtChange();
        },
        "isNavShow":function(){
            this.scrollHeight= -97 + (this.isNavShow?0:55)+"" ; //-97 -129,
        }
    },
    activated () {
    },
    created() {
        this.scrollHeight= -97 + (this.isNavShow?0:55)+"" ;
        this.getData();
        document.querySelector('#vux_view_box_body').scrollTop = 0 ;
        this.initPage();
		this.$store.commit({ type: "z39/addTaskExt", value: {} });
    },
    filters: {  
        dayLetter: function (day) {  
          //var today = moment().format("YYYY-MM-DD");
          var nextDay = moment().add(1,"d").format("YYYY-MM-DD");
          var letter =day;
          if(day =="" || day == nextDay) letter = "明天";
          else if(day == this.today) letter = "今天";
          return letter ;
        },
    },
    mounted: function() {        
        this.getInitData();
        this.getLocalData();
        let time = moment().format("H");
        time = parseInt(time) ;
        let temp ;
        if( time >= 12 )temp=moment().add(1, 'days').format("YYYY-MM-DD");
        else temp = moment().format("YYYY-MM-DD");
        this.showMonth = temp ;
    },
    methods: {
        taskAddExtChange(){
            let data = {} ;
            let tags = {};
            if( this.btnType == 1 ){ //周 任务添加 s 
                data.state = "due" ;
                let temp = this.filtersDue ;
                let firstDay = temp[0] ;
                let lastDay = temp[6] ;
                let tomorrow = moment().add(1,'d').format('YYYY-MM-DD') ;
                tags.due = firstDay > tomorrow ? firstDay :(lastDay < tomorrow ? lastDay : tomorrow) ;
            }else if( this.btnType == 2 || this.btnType == 3  ){   //年 月 
                data.state = "due" ;
                tags.due = this.filterDue ;
            }
            data.tags = tags ;
            console.log("taskAddExtChange;",data);
            this.taskAddExt=data;
			this.$store.commit({ type: "z39/addTaskExt", value: data });
        },
		getInitData(){
			if( _.isEmpty(this.tagitemDic) && this.uid >0 ){
				this.tagitemsGet();
			}
		},
        initPage(){
            document.querySelector('#vux_view_box_body').scrollTop = 0 ;
            this.nonesCpted();
        },
        nonesCpted(){
            let runtimeNones = localStorage.getItem('timeNones');
            let tempNow = new Date().getTime();
            if( runtimeNones != undefined && tempNow-runtimeNones<10) return ;
            var len = this.taskAll.length ;
            localStorage.setItem('timeNones',tempNow);
            let temp = [] ;
            if( this.btnType ==0 ){  //获取未计划的任务.
                temp = this.taskAll.filter(task=> {return task.uid == this.uid && (task.state == '' || task.state == 'started') && task.parid == null && task.pid == null && !( task.tags && task.tags["due"]) } ) ;
            }else{
                var filterDue = this.filterDue ;
                var filtersDue = this.filtersDue ;
                var len = this.taskAll.length ;
                var needTotal = 0;
                var timeDic= {},numDic={},d,w1,w2 ;
                if(this.btnType==2){ //月计划分为4周
                    w1 = moment(this.filterDue+"-01").isoWeek();
                    w2 = moment(this.filterDue+"-01").endOf('month').isoWeek();
                    for(var j=w1;j<=w2;j++) numDic[j]=0;                    
                }
                //if(numDic[d]==undefined) numDic[d]=0;
                for(var i=0;i<= len-1 ;i++){
                    var t = this.taskAll[i] ;                
                    if( t.uid == this.uid && (t.state !='done' && t.state !='started'&& t.state !='cancelled') && t.parid == null && t.tags && t.tags['due'] != undefined ){
                        d = t.tags.due.substr(0,10); //适合周计划中的每天
                        if(this.btnType==2) d=moment(d).isoWeek();
                        if(numDic[d]==undefined) numDic[d]=0;
                        numDic[d] +=1;
                        if (t.tags && t.tags.need && (this.btnType==1||this.btnType==2 )) {
                            //needTotal += parseInt(t.tags.need);
                            if(timeDic[d]==undefined) timeDic[d]=0;
                            timeDic[d] += parseInt(t.tags.need);
                        }
                        var due = t.tags['due'] ;
                        if( this.btnType != 1 ){
                            if( due.indexOf(filterDue) > -1 ) temp.push(t) ;
                        }else{
                            var len1 = filtersDue.length ;
                            for(var j=0;j<= len1-1 ;j++){
                                var dueitem = filtersDue[j] ;
                                if( due.indexOf(dueitem) > -1 ) temp.push(t) ;
                            }
                        }
                    }
                }
                var needstr = "",total;
                for(var d in numDic){ //只有btnType=1或2 
                    total = timeDic[d]?formatUsed(timeDic[d]):"0m";
                    if(this.btnType==1){
                        needstr += `${d.substr(8)}号 ${numDic[d]}个 评估${total}\n</br>`;
                    }else if(this.btnType==2){
                        let d1 = moment().week(d).day("Monday").format("DD");
                        let d7 = moment().week(d).day("Sunday").add(7,"d").format("DD");
                        needstr += `${d1}~${d7}号 ${numDic[d]}个 评估${total}\n</br>`;
                    }
                }
                //needTotal = formatUsed(needTotal);
                //this.$vux.toast.text("评估耗时 "+needTotal);
                if(needstr)this.$vux.toast.text(needstr);
                temp = _.sortBy(temp,a=>{return a.tags.due})
            }

            if( !firstrun && len<defaultTask.length){  //显示默认数据
                var alls = this.taskAll.map(t=>{return t.title})
                defaultTask.map(t=>{if(alls.indexOf(t.title) == -1) temp.push(t);})
                if(!len&&temp.length==defaultTask.length) autoOpenid= setTimeout(()=>{ this.$refs.action[2].open("left")},1000);
                console.log("action open");
            }else if(this.$refs.action && this.$refs.action.length>2){
                if(this.$refs.action[2].direction=="left") this.$refs.action[2].close();
                clearTimeout(autoOpenid);
                console.log("action close");
            }

            this.pageTotal = temp.length / this.pageNumOne ;
            // this.pullStatus.pullupStatus = this.pageTotal <= 1?"disabled":"enabled" ;
            if(this.pageTotal <= 1)setTimeout(() => {this.$refs.scroll.disablePullup();}, 100)
            else setTimeout(() => {this.$refs.scroll.enablePullup();}, 100)
            
            this.nonesArr = temp ;
            this.nonesLen = temp.length ;

            var taskLen = this.nonesLen ;
            let _this =this ;
            if(taskLen<lastTaskLen ){
                this.$vux.bus.$emit('addTodayNum', null);
            }
            lastTaskLen = taskLen ;

            var todayDot=this.taskAll.some(t=> {return t.state!="done" && t.state!="cancelled" && t.uid ==_this.uid && t.tags && t.tags["due"] && t.tags["due"].indexOf(this.today) !=-1} );
            this.$vux.bus.$emit('todayNum', {today:todayDot});

            this.$nextTick(() => {this.$refs.scroll.reset()})
            console.log("nonesCpted in ",temp.length);
            return temp;
        },
        goTask(item,index){ // 进入任务详情
            if(!item.id) return this.addDemoTask(item,"").then(data=>{item.id = data.id,this.$router.push(`/taskDetail/${item.id}`) ;}) ;
            this.$router.push(`/taskDetail/${item.id}`) ;
            // this.$router.push(`taskDetail`) ;
        },
        onDelClick(item,index){
            if(!item.id) return this.addDemoTask(item,"cancelled");
            this.doTaskEdit(item,"cancelled",moment().format("YYYY-MM-DD HH:mm"));
            this.tongji("task","cancelled","todo","click");
        },
        actionOpenDone(item,index,option){            
            let dir = "" , target , arrIndex = index ;
            target = this.$refs.action[index] ;
            dir = target.direction ;
            if( dir == "left"){
                if(!item.id) return this.addDemoTask(item, "done"),setTimeout(() => {target.close()}, 200);
                if( item.state == "done"){
                    this.doTaskEdit(item,"");
                    this.tongji("task","cancelled","todo","swipe");
                }else{
                    this.doTaskEdit(item,"done",moment().format("YYYY-MM-DD HH:mm"));
                    this.tongji("task","done","todo","swipe");
                }
                setTimeout(() => {target.close()}, 200); //自动关闭
            }
        },
        actionSwipeDone(item,index){
            if(!item.id) return this.addDemoTask(item, "done"),setTimeout(() => {target.close()}, 200);
        },
        onBtn(item){

        },
        onSortItem(item,index,type){
            if( type == 1 ) this.btnType = 1 ;            
            this.tongji("task","vip","todo",type);
            var day ;
            if(this.btnType==1){
                this.filtersDue = item.value.split('|') ;
                day = this.filtersDue[this.filtersDue.length-1];
            }else{
                this.filterDue=item.value ;
                day=moment(item.value).endOf('month').format("YYYY-MM-DD");
            }
            this.tasksGet({key:'due:'+item.value}).then(data=>{
                 this.nonesCpted();  
            }) ;
            this.lastAreaDay =day ;
            this.$store.commit({ type: "z39/addTaskExt", value: {state:"due",tags:{due:day}} });
            console.log("onSortItem",item.value,index,this.filtersDue,this.lastAreaDay) ;
        },
        onTypeChange(index){
            if(index == 0){
                this.weekSelectLast = this.weekSelect >-1 ? this.weekSelect:0;
                this.weekSelect = -1 ;
                this.nonesCpted();
                this.$store.commit({ type: "z39/addTaskExt", value: {} });
            }else if(index == 1){
                this.weekSelect = this.weekSelectLast ;
                this.$refs.weeks[this.weekSelect].$emit("on-item-click");
            }else if(index == 2){                
                this.$refs.months[this.monthSelect].$emit("on-item-click");
            }else if(index == 3){                
                this.$refs.years[this.yearSelect].$emit("on-item-click");
            }
            localStorage.setItem("todoType",moment().format("YYYY-MM-DD")+"_"+index);
            console.log("ontype:", index,this.weekSelect);
        },
        getWeekDays(weekTh,yearTh){
            weekTh = weekTh || moment().isoWeek();
            yearTh = yearTh || moment().format("YYYY") ;
            // console.log("week",moment().week(weekTh).day("Monday").format("YYYY-MM-DD"))
            let firstDay = moment().week(weekTh).day("Monday");
            let day1 = firstDay.format("YYYY-MM-DD");
            let res = [day1] ;
            for(var i=1;i<= 6 ;i++){
                res.push( firstDay.add( 1,'d').format("YYYY-MM-DD") );
            }
            // let day7 = moment(yearTh + '-01-01').add((weekTh -1)*7 +6, 'd').format("YYYY-MM-DD");
            return res; //[day1,day7] ;
        },
        getWeekRec(weekNum){   //获取最近几周 , 默认5周
            weekNum = weekNum || 5 ;
            let weekCurr = moment().isoWeek();
            let res = [] ;
            var len = weekNum ,temp ,day1,day7 ;
            var label , value ,week ;
            for(var i=0;i<= len-1 ;i++){
                temp = this.getWeekDays( weekCurr + i) ;
                day1 = moment(temp[0]) ;
                day7 = moment(temp[6]) ;
                if( i == 0 ){
                    label = "本周";
                }else if(i ==1){
                    label = "下周";
                }else{
                    label = day1.format("M") + "." + day1.format("D") + "-" +  day7.format("D") ;
                }
                res.push({label:label,value:temp.join("|"), week: day1.isoWeek(),month: day1.format("YYYY-MM")}) ;
            }
            return res ;  //这周、下周、9.24-30 10.1-7 10.8-16
        },  
        getMonthRec(monthNum){   //获取最近几个月 , 默认12个月
            monthNum = monthNum || 12 ;
            let nowM = moment() ;
            let year = nowM.year();
            let monthCurr = nowM.month();
            let res = [] ;
            var len = monthNum ,temp ,day1,day7 ;
            var label , value  ;
            for(var i=0;i<= len-1 ;i++){
                if( i == 0 ){
                    temp = nowM ;
                }else{
                    temp =nowM.add( 1,'M') ;
                }                  
                label = temp.format("M") ;
                label = nowM.year()==year? label: "+"+ label; //nowM.add(1,"y").format("YY-M"); // 
                res.push({label:label,value:temp.format("YYYY-MM")}) ;
            }
            return res ;  //这周、下周、9.24-30 10.1-7 10.8-16
        },  
        getYearRec(yearNum){   //获取最近几年 , 默认5年
            yearNum = yearNum || 5 ;
            let nowM = moment() ;
            // let year = nowM.years();
            let res = [] ;
            var len = yearNum ,temp ;
            var label , value  ;
            for(var i=0;i<= len-1 ;i++){
                if( i == 0 ){
                    temp = nowM ;
                }else{
                    temp = nowM.add( 1,'Y') ;
                }                
                label = temp.format("YYYY") ;
                res.push({label:label,value:label}) ;
            }
            return res ;  //这周、下周、9.24-30 10.1-7 10.8-16
        },  
        getData: function() {
            this.weekBtns =  this.getWeekRec() ;
            this.monthBtns = this.getMonthRec() ;
            this.yearBtns = this.getYearRec() ;
            console.log( this.getWeekRec() ) ;
        },
        getLocalData(){            
            var vip = localStorage.getItem("todoVip");
            if( vip && this.today!=vip) localStorage.removeItem("todoVip");
            else if(vip) this.changeVip();// this.mode_vip = true ;
            else return; //如果vip都没运行,后面的逻辑更不会进入.
            var type = localStorage.getItem("todoType");
            if(type && this.today!=type.split("_")[0]) localStorage.removeItem("todoType");
            else if(type) {
                this.btnType = parseInt(type.split("_")[1]) ;
                this.$nextTick(() => {
                    setTimeout(()=>{this.onTypeChange(this.btnType)},200)
                }); 
            }
        },
        loadNext(){
            console.log("loadNext");
            if( this.pageIndex < this.pageTotal ){
                this.pageIndex ++ ;
                this.pageShowNum = this.pageIndex * this.pageNumOne ;
                // console.log("pageShowNum",this.pageShowNum) ;
                this.$refs.scroll.donePullup() ;
                this.tongji("task","nextpage","todo",this.pageIndex);
            }
			this.checkClosePullup();
        },
		checkClosePullup(){
            this.$refs.scroll.reset();
			if( this.pageIndex >= this.pageTotal){
				setTimeout(() => {
					this.$refs.scroll.disablePullup()
				}, 100)	
			}
		},
        changeVip(){
            this.$nextTick(() => {
                setTimeout(() => {
                    this.scrollHeight = -129 + (this.isNavShow?0:55)+"" ; 
                    this.$refs.scroll.reset();
                    this.$refs.scroll.donePulldown()
                    // this.$refs.scroll.disablePulldown() ; //报错没有此方法.
                  }, 10)
                setTimeout(() => {
                    this.tongji("task","vip","todo","");
                    localStorage.setItem("todoVip",moment().format("YYYY-MM-DD"));
                    this.mode_vip = true ;
                }, 200)                
            })
        },
        taskAddVis(val){
            this.showTaskAdd = val ;
            this.weekEdit = val ;
        },
        ...mapActions([
            
        ])
    },
    data() {
        return {
            pageName:"todo",
            nonesArr:[] ,
            nonesLen:0,
            showMonth:'',
            weekEdit:false ,
            btnType:0 ,
            btns:["无","周","月","年"],
            weekBtns:[], //["这 周","下一周","9.24-30","10.1-7","10.8-16"],
            monthBtns:["9","10","11","12","明1","明2","明3"],
            yearBtns:["17","18","19","20","21","22","23"],
            btnsShow:false ,
            taskArr:[],
            weekSelect:-1,
            weekSelectLast:0,
            monthSelect:0,
            yearSelect:0,
            filterDue:'',
            filtersDue:[],
            mode_vip:false,
            pageIndex: 1 ,
            pageTotal: 2 ,
            pageShowNum:15,
            pageNumOne: 15 ,
              pullupConfig2: {
                content: '上拉加载更多',
                downContent: '松开进行加载',
                upContent: '上拉加载更多',
                loadingContent: '加载中...'
              },
            pullStatus: {
             pullupStatus: 'default',
             pulldownStatus: 'default'
            },
            pullDownConfig2: {
                content: '松开切换模式',
                downContent: 'VIP高级模式',
                upContent: '下拉进入高级模式',
                loadingContent: '切换中...'
              },
            scrollHeight: -97, //-97 -129,
            showTaskAdd:false,
            taskAddExt:{},
            lastAreaDay:null,
        }
    }
}

</script>
<style scoped>

.day-item {
  border: 1px solid #ececec;
  padding: 5px 15px;
}
.day-item-selected {
  border: 1px solid green;
}

</style>
<style>


#p_none .weui-search-bar:before {
    height: 0;
    border-top: 0;
}
#p_none .vux-tab {
    padding:2px 6px ;
    height: 32px;
}
#p_none .vux-tab .vux-tab-item{
    background: #fff;
    line-height: 28px;    font-size: 16px;
}
#p_none .vux-tab .vux-tab-selected {
    background: rgba(0, 169, 255, 0.24);border-radius: 6px;
}
#p_none .vux-tab .next {
    background: rgba(238, 238, 238, 0.7);
}

#p_none .timeBtn{width:180px;padding-left: 4px;background-color: #fff;padding-top: 2px;}
#p_none .timeBtn  > a { height: 28px; line-height: 28px; }

</style>